package org.example.rabbitmq.publicsubscribe;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;

public class ReceiveLogs {
    private static final String EXCHANGE_NAME = "logs";

    public static void main(String[] argv) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("192.168.0.228");
        factory.setUsername("mq");
        factory.setPassword("123456");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        // 声明一个名为EXCHANGE_NAME的交换机，类型为fanout。fanout交换机将接收到的消息广播到所有绑定的队列，不进行任何路由判断。
        channel.exchangeDeclare(EXCHANGE_NAME, "fanout");

        // 声明一个独占的、非持久化的、自动删除的队列，并获取系统分配的队列名称。
        // 这个队列用于临时接收消息，当消费者断开连接时，队列会被自动删除。
        String queueName = channel.queueDeclare().getQueue();

        // 将上述声明的队列与之前声明的交换机EXCHANGE_NAME绑定，但不指定路由键（routing key为空字符串）。
        // 这是因为fanout类型的交换机忽略路由键，会将所有消息广播到绑定的所有队列。
        channel.queueBind(queueName, EXCHANGE_NAME, "");

        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), "UTF-8");
            System.out.println(" [x] Received '" + message + "'");
        };
        channel.basicConsume(queueName, true, deliverCallback, consumerTag -> { });
    }
}
